package com.ctshk.rpc.airexpress.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.*;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.rpc.airexpress.constants.ResourceConstants;
import com.ctshk.rpc.airexpress.dto.*;
import com.ctshk.rpc.airexpress.dto.app.TicketNameDTO;
import com.ctshk.rpc.airexpress.entity.*;
import com.ctshk.rpc.airexpress.mapper.*;
import com.ctshk.rpc.airexpress.req.*;
import com.ctshk.rpc.airexpress.req.cache.CacheOpsReq;
import com.ctshk.rpc.airexpress.service.AirportExpressService;
import com.ctshk.rpc.airexpress.service.IAirportExpressAppService;
import com.ctshk.rpc.airexpress.service.IAirportExpressService;
import com.ctshk.rpc.system.dto.SysAgentQueryListDTO;
import com.ctshk.rpc.system.dto.SysDepartmentDTO;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.req.SysAgentQueryListReq;
import com.ctshk.rpc.system.service.ISysAgentService;
import com.ctshk.rpc.system.service.ISysDepartmentService;
import com.ctshk.rpc.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Slf4j
@DubboService
public class AirportExpressServiceImpl extends ServiceImpl<AirportExpressMapper, AirportExpress> implements IAirportExpressService {
    @Autowired
    private AirportExpressMapper airportExpressMapper;
    @Autowired
    private AirportExpressIncreaseStrategyMapper airportExpressIncreaseStrategyMapper;
    @Autowired
    private AirportExpressIncreaseStrategyDateMapper airportExpressIncreaseStrategyDateMapper;
    @Autowired
    private AirportExpressIncreaseStrategyRuleMapper airportExpressIncreaseStrategyRuleMapper;
    @Autowired
    private AirportExpressChannelOfflineAgentCustomMapper airportExpressChannelOfflineAgentCustomMapper;
    @Autowired
    private AirportExpressChannelOfflineSelfCustomMapper airportExpressChannelOfflineSelfCustomMapper;
    @Autowired
    private AirportExpressChannelOnlineSelfPlatformMapper airportExpressChannelOnlineSelfPlatformMapper;
    @Autowired
    private AirportExpressChannelOnlineThirdPlatformMapper airportExpressChannelOnlineThirdPlatformMapper;
    @Autowired
    private AirportExpressInitializationSettingsMapper airportExpressInitializationSettingsMapper;
    @Autowired
    private AirportExpressInitializationSettingsChannelMapper airportExpressInitializationSettingsChannelMapper;
    @DubboReference
    private ISysDepartmentService sysDepartmentService;
    @DubboReference
    private ISysAgentService sysAgentService;
    @DubboReference
    private ISysUserService sysUserService;
    @DubboReference
    private IAirportExpressAppService airportExpressAppService;

    @Override
    public Result<List<AirportExpressDTO>> selectResourceList() {
        List<AirportExpress> airportExpressList = airportExpressMapper.selectList(new QueryWrapper<AirportExpress>().lambda()
                .orderByAsc(AirportExpress::getGmtCreate)
                .eq(AirportExpress::getIsDeleted, IsDeletedCode.NO.getCode())
                .select(AirportExpress::getId, AirportExpress::getProductCode, AirportExpress::getTicketTypeNameCn, AirportExpress::getTicketTypeNameEn,
                        AirportExpress::getTicketType, AirportExpress::getSource, AirportExpress::getSupplierId, AirportExpress::getSupplierName,
                        AirportExpress::getAdultPrice, AirportExpress::getChildrenPrice, AirportExpress::getChargePersonName,
                        AirportExpress::getChargePersonDepartment, AirportExpress::getSaleStatus, AirportExpress::getOnShelfStatus));
        List<AirportExpressDTO> airportExpressDTOs = EntityUtil.copyList(airportExpressList, AirportExpressDTO.class);
        return Result.success(airportExpressDTOs);
    }

    @Override
    public Result<List<AirportExpressDTO>> selectProductList() {
        List<AirportExpress> airportExpressList = airportExpressMapper.selectList(new QueryWrapper<AirportExpress>().lambda()
                .orderByAsc(AirportExpress::getGmtCreate)
                .eq(AirportExpress::getIsDeleted, IsDeletedCode.NO.getCode())
                .eq(AirportExpress::getSaleStatus, SaleOnShelfStatusCode.SALE_STATUS_1.getCode())
                .eq(AirportExpress::getOnShelfStatus, SaleOnShelfStatusCode.ON_SHELF_STATUS_1.getCode())
                .select(AirportExpress::getId, AirportExpress::getProductCode, AirportExpress::getTicketTypeNameCn, AirportExpress::getTicketTypeNameEn,
                        AirportExpress::getSupplierId, AirportExpress::getSupplierName, AirportExpress::getChargePersonName,
                        AirportExpress::getChargePersonDepartment, AirportExpress::getSaleStatus, AirportExpress::getOnShelfStatus));
        List<AirportExpressDTO> airportExpressDTOs = EntityUtil.copyList(airportExpressList, AirportExpressDTO.class);
        return Result.success(airportExpressDTOs);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result updateBatch(AirportExpressUpdateBatchReq airportExpressUpdateBatchReq, Long userId) {
        LocalDateTime now = LocalDateTime.now();
        UserDTO chargeUser = sysUserService.queryCacheUser(airportExpressUpdateBatchReq.getChargePersonId());
        if (chargeUser == null) {
            throw new BusinessException(SystemError.SYS_411);
        }
        for (Long id : airportExpressUpdateBatchReq.getAirportExpressIdList()) {
            UpdateWrapper<AirportExpress> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", id);
            updateWrapper.lambda().set(AirportExpress::getSaleStatus, airportExpressUpdateBatchReq.getSaleStatus());
            updateWrapper.lambda().set(AirportExpress::getChargePersonId, airportExpressUpdateBatchReq.getChargePersonId());
            updateWrapper.lambda().set(AirportExpress::getChargePersonName, chargeUser.getFullName());
            updateWrapper.lambda().set(AirportExpress::getChargePersonNumber, chargeUser.getEmployeeNumber());
            updateWrapper.lambda().set(AirportExpress::getChargePersonDepartment, chargeUser.getDept());
            updateWrapper.lambda().set(AirportExpress::getModifiedId, userId);
            updateWrapper.lambda().set(AirportExpress::getGmtModified, now);
            int i = airportExpressMapper.update(null, updateWrapper);
            if (i != 1) {
                throw new BusinessException(SystemError.SYS_437);
            }
        }
        /**
         * 更新redis缓存
         */
        CompletableFuture.runAsync(() -> {
            log.info("【机场快线-批量更新API设置】更新redis缓存, data:{}", JSON.toJSONString(airportExpressUpdateBatchReq.getAirportExpressIdList()));
            airportExpressAppService.cacheInit();
        });
        return Result.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result update(AirportExpressUpdateReq airportExpressUpdateChargePriceReq, Long userId) {
        AirportExpress airportExpress = EntityUtil.copy(airportExpressUpdateChargePriceReq, AirportExpress.class);
        UserDTO chargeUser = sysUserService.queryCacheUser(airportExpress.getChargePersonId());
        airportExpress.setChargePersonName(chargeUser.getFullName());
        airportExpress.setChargePersonNumber(chargeUser.getEmployeeNumber());
        airportExpress.setChargePersonDepartment(chargeUser.getDept());
        airportExpress.setModifiedId(userId);
        airportExpress.setGmtModified(LocalDateTime.now());
        int i = airportExpressMapper.updateById(airportExpress);
        if (i != 1) {
            throw new BusinessException(SystemError.SYS_437);
        }
        /**
         * 更新redis缓存
         */
        CompletableFuture.runAsync(() -> {
            log.info("【机场快线-更新API设置】更新redis缓存, data:{}", airportExpressUpdateChargePriceReq.getId());
            airportExpressAppService.cacheInit();
        });
        return Result.success(airportExpressUpdateChargePriceReq.getId());
    }

    @Override
    public Result updateSaleStatus(AirportExpressUpdateSaleStatusReq airportExpressUpdateSaleStatusReq, Long userId) {
        UpdateWrapper<AirportExpress> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", airportExpressUpdateSaleStatusReq.getId());
        updateWrapper.lambda().set(AirportExpress::getSaleStatus, airportExpressUpdateSaleStatusReq.getSaleStatus());
        updateWrapper.lambda().set(AirportExpress::getModifiedId, userId);
        updateWrapper.lambda().set(AirportExpress::getGmtModified, LocalDateTime.now());
        int i = airportExpressMapper.update(null, updateWrapper);
        if (i != 1) {
            throw new BusinessException(SystemError.SYS_437);
        }
        /**
         * 更新redis缓存
         */
        CompletableFuture.runAsync(() -> {
            log.info("【机场快线-更新售卖状态】更新redis缓存, data:{}", airportExpressUpdateSaleStatusReq.getId());
            airportExpressAppService.cacheInit();
        });
        return Result.success();
    }

    @Override
    public Result<List<AirportExpressReservationDTO>> selectReservationList(Long userId) {
        List<IncreaseStrategyRuleTempDTO> strategyRuleList = getStrategyRuleList(userId, Channel.AUTARKY);
        List<AirportExpressReservationDTO> airportExpressReservationDTOS = EntityUtil.copyList(strategyRuleList, AirportExpressReservationDTO.class);
        return Result.success(airportExpressReservationDTOS);
    }

    /**
     * 获取产品价格
     *
     * @param userId
     * @param channel
     * @return
     */
    private List<IncreaseStrategyRuleTempDTO> getStrategyRuleList(Long userId, Channel channel) {
        LocalDate nowDate = LocalDate.now();
        List<IncreaseStrategyRuleTempDTO> increaseStrategyRuleTempDTOs = new ArrayList<>();
        List<AirportExpress> airportExpressList = airportExpressMapper.selectList(new QueryWrapper<AirportExpress>().lambda()
                .orderByAsc(AirportExpress::getGmtCreate)
                .eq(AirportExpress::getIsDeleted, IsDeletedCode.NO.getCode())
                .eq(AirportExpress::getOnShelfStatus, SaleOnShelfStatusCode.ON_SHELF_STATUS_1.getCode())
                .eq(AirportExpress::getSaleStatus, SaleOnShelfStatusCode.SALE_STATUS_1.getCode()));
        if (CollectionUtils.isEmpty(airportExpressList)) {
            return increaseStrategyRuleTempDTOs;
        }
        List<Long> airExpressIds = airportExpressList.stream().map(AirportExpress::getId).collect(Collectors.toList());
        // 查询产品当前日期的策略
        List<AirportExpressIncreaseStrategy> airportExpressIncreaseStrategies = airportExpressIncreaseStrategyMapper.selectByAirportExpressIdsNowDate(airExpressIds, nowDate.toString());
        // 查询API初始化配置
        AirportExpressInitializationSettings airportExpressInitializationSettings = airportExpressInitializationSettingsMapper.selectCheckSetting(channel.getCode());
        int remainderNumber = 0;

        for (AirportExpress airportExpress : airportExpressList) {
            IncreaseStrategyRuleTempDTO rule = EntityUtil.copy(airportExpress, IncreaseStrategyRuleTempDTO.class);
            // 查询机场快线-当前日期的加幅策略
            AirportExpressIncreaseStrategy airportExpressIncreaseStrategy = null;
            AirportExpressIncreaseStrategyRule aeIncreaseStrategyRule = null;
            for (AirportExpressIncreaseStrategy increaseStrategy : airportExpressIncreaseStrategies) {
                if (Objects.equals(airportExpress.getId(), increaseStrategy.getAirportExpressId())) {
                    airportExpressIncreaseStrategy = increaseStrategy;
                    aeIncreaseStrategyRule = getOfflineSelfRule(userId, rule, airportExpressIncreaseStrategy);
                    break;
                }
            }
            if (rule.isIfDisabledSale()) {
                continue;
            }
            if (aeIncreaseStrategyRule == null && airportExpressInitializationSettings != null) {
                // 机场快线-按照初始化设置查询加幅规则
                aeIncreaseStrategyRule = EntityUtil.copy(airportExpressInitializationSettings, AirportExpressIncreaseStrategyRule.class);
                // 默认售票数量无限制
                aeIncreaseStrategyRule.setSaleableType(1);
            }
            // 加幅規則不爲空，构建产品销售价格
            if (aeIncreaseStrategyRule != null) {
                remainderNumber = buildRemainderNumber(aeIncreaseStrategyRule);
                HashMap<Integer, BigDecimal> priceMap = AirportExpressService.buildIncreasePrice(airportExpress, aeIncreaseStrategyRule, channel.getCode());
                rule.setAdultPrice(priceMap.get(0));
                rule.setChildrenPrice(priceMap.get(1));
                rule.setSaleableType(aeIncreaseStrategyRule.getSaleableType());
                rule.setRemainderNumber(remainderNumber);
                increaseStrategyRuleTempDTOs.add(rule);
            }
        }
        return increaseStrategyRuleTempDTOs;
    }

    private AirportExpressIncreaseStrategyRule getOfflineSelfRule(Long userId, IncreaseStrategyRuleTempDTO rule, AirportExpressIncreaseStrategy airportExpressIncreaseStrategy) {
        if (Objects.equals(airportExpressIncreaseStrategy.getSelfSalePermissionType(), OrderAirexpressConstants.SALE_CHANNEL_TYPE_DISABLED)) {
            // 自营禁售
            rule.setIfDisabledSale(true);
            return null;
        } else if (Objects.equals(airportExpressIncreaseStrategy.getSelfSalePermissionType(), OrderAirexpressConstants.SALE_CHANNEL_TYPE_ALL)) {
            //当前机场快线-线下自营所有-获取加幅规则
            return airportExpressIncreaseStrategyRuleMapper.selectById(airportExpressIncreaseStrategy.getSelfSalePermissionId());
        } else if (Objects.equals(airportExpressIncreaseStrategy.getSelfSalePermissionType(), OrderAirexpressConstants.SALE_CHANNEL_TYPE_SELECTED)) {
            //当前机场快线-线下自营选中-获取加幅规则
            List<AirportExpressChannelOfflineSelfCustom> channelOfflineSelfCustomList = airportExpressChannelOfflineSelfCustomMapper.selectList(new QueryWrapper<AirportExpressChannelOfflineSelfCustom>().lambda()
                    .eq(AirportExpressChannelOfflineSelfCustom::getIncreaseStrategyId, airportExpressIncreaseStrategy.getId())
                    .eq(AirportExpressChannelOfflineSelfCustom::getIsDeleted, IsDeletedCode.NO.getCode()));
            for (AirportExpressChannelOfflineSelfCustom channelOfflineSelfCustom : channelOfflineSelfCustomList) {
                Long relationId = channelOfflineSelfCustom.getRelationId();
                List<Long> deptIds;
                if (channelOfflineSelfCustom.getCheckType() == 1) {
                    // 根据用户ID查询所有上级部门ID
                    deptIds = sysDepartmentService.queryIdsByUserId(relationId);
                } else {
                    // 根据部门ID查询所有上级部门ID
                    deptIds = sysDepartmentService.queryIdsById(relationId);
                }
                for (Long deptId : deptIds) {
                    // 查询部门下的用户ID
                    List<Long> userIds = sysDepartmentService.queryCUserIdsByDeptId(deptId);
                    if (userIds.contains(userId)) {
                        // 当前机场快线-线下自营选中-查询加幅规则
                        return airportExpressIncreaseStrategyRuleMapper.selectOne(new QueryWrapper<AirportExpressIncreaseStrategyRule>().lambda()
                                .eq(AirportExpressIncreaseStrategyRule::getCustomId, channelOfflineSelfCustom.getId()));
                    }
                }
            }
        }
        return null;
    }

    @Override
    public Result<List<AirportExpressReservationAgentDTO>> selectReservationAgentListById(Long id) {
        // 查询机场快线
        AirportExpress airportExpress = airportExpressMapper.selectById(id);
        if (airportExpress == null) {
            // 无机场快线
            throw new BusinessException(SystemError.AIREXPRESS_50004);
        }
        List<AirportExpressReservationAgentDTO> reservationAgentDTOList = new ArrayList<>();
        // 查询机场快线-当前日期加幅策略
        AirportExpressIncreaseStrategy airportExpressIncreaseStrategy = airportExpressIncreaseStrategyMapper.selectByAirportExpressIdNowDate(id, LocalDate.now().toString());
        if (airportExpressIncreaseStrategy != null) {
            if (airportExpressIncreaseStrategy.getAgentSalePermissionType() == null) {
                return Result.success(reservationAgentDTOList);
            }
            // 代理禁售
            if (airportExpressIncreaseStrategy.getAgentSalePermissionType() == OrderAirexpressConstants.SALE_CHANNEL_TYPE_DISABLED) {
                return Result.success(null);
            } else if (airportExpressIncreaseStrategy.getAgentSalePermissionType() == OrderAirexpressConstants.SALE_CHANNEL_TYPE_ALL) {
                // 当前机场快线-线下自营所有-获取加幅规则
                AirportExpressIncreaseStrategyRule aeIncreaseStrategyRule = airportExpressIncreaseStrategyRuleMapper.selectById(airportExpressIncreaseStrategy.getAgentSalePermissionId());
                int remainderNumber = buildRemainderNumber(aeIncreaseStrategyRule);
                if (aeIncreaseStrategyRule.getSaleableType() == OrderAirexpressConstants.SALE_TYPE_LIMIT && remainderNumber <= 0) {
                    // 余票为0，代理商加幅规则失效
                    return Result.success(null);
                } else {
                    // 获取所有代理商
                    List<SysAgentQueryListDTO> sysAgentQueryListDTOs = getSysBigClientQueryListDTOS();
                    if (CollectionUtils.isNotEmpty(sysAgentQueryListDTOs)) {
                        for (SysAgentQueryListDTO sysAgentQueryListDTO : sysAgentQueryListDTOs) {
                            AirportExpressReservationAgentDTO airportExpressReservationAgentDTO = new AirportExpressReservationAgentDTO();
                            airportExpressReservationAgentDTO.setId(sysAgentQueryListDTO.getId());
                            airportExpressReservationAgentDTO.setAgentName(sysAgentQueryListDTO.getGroupCnName());
                            airportExpressReservationAgentDTO.setSaleableType(aeIncreaseStrategyRule.getSaleableType());
                            airportExpressReservationAgentDTO.setRemainderNumber(remainderNumber);
                            HashMap<Integer, BigDecimal> priceMap = AirportExpressService.buildIncreasePrice(airportExpress, aeIncreaseStrategyRule, Channel.AGENT.getCode());
                            airportExpressReservationAgentDTO.setAdultPrice(priceMap.get(0));
                            airportExpressReservationAgentDTO.setChildrenPrice(priceMap.get(1));
                            reservationAgentDTOList.add(airportExpressReservationAgentDTO);
                        }
                    }
                }
            } else if (airportExpressIncreaseStrategy.getAgentSalePermissionType() == OrderAirexpressConstants.SALE_CHANNEL_TYPE_SELECTED) {
                //当前机场快线-线下代理选中-获取代理加幅规则列表
                QueryWrapper<AirportExpressChannelOfflineAgentCustom> offlineAgentQueryWrapper = new QueryWrapper<>();
                offlineAgentQueryWrapper.lambda().eq(AirportExpressChannelOfflineAgentCustom::getIncreaseStrategyId, airportExpressIncreaseStrategy.getId());
                List<AirportExpressChannelOfflineAgentCustom> airportExpressChannelOfflineAgentCustom = airportExpressChannelOfflineAgentCustomMapper.selectList(offlineAgentQueryWrapper);
                if (CollectionUtils.isNotEmpty(airportExpressChannelOfflineAgentCustom)) {
                    // 获取所有代理商
                    List<SysAgentQueryListDTO> sysAgentQueryListDTOs = getSysBigClientQueryListDTOS();
                    for (AirportExpressChannelOfflineAgentCustom aeChannelOfflineAgentCustom : airportExpressChannelOfflineAgentCustom) {
                        // 选机场快线代理列表在系统代理商列表中是否存在
                        SysAgentQueryListDTO sysAgentQueryListDTO = sysAgentQueryListDTOs.stream().filter(sysbig -> Objects.equals(sysbig.getId(), aeChannelOfflineAgentCustom.getAgentId())).findAny().orElse(null);
                        if (sysAgentQueryListDTO != null) {
                            // 当前机场快线-线下代理选中-查询加幅规则
                            QueryWrapper<AirportExpressIncreaseStrategyRule> ruleQueryWrapper = new QueryWrapper<>();
                            ruleQueryWrapper.lambda().eq(AirportExpressIncreaseStrategyRule::getCustomId, aeChannelOfflineAgentCustom.getId());
                            AirportExpressIncreaseStrategyRule aeIncreaseStrategyRule = airportExpressIncreaseStrategyRuleMapper.selectOne(ruleQueryWrapper);
                            int remainderNumber = buildRemainderNumber(aeIncreaseStrategyRule);
                            if (aeIncreaseStrategyRule.getSaleableType() == OrderAirexpressConstants.SALE_TYPE_LIMIT && remainderNumber <= 0) {
                                // 余票为0, 代理商失效
                                continue;
                            }
                            AirportExpressReservationAgentDTO airportExpressReservationAgentDTO = new AirportExpressReservationAgentDTO();
                            airportExpressReservationAgentDTO.setId(aeChannelOfflineAgentCustom.getId());
                            airportExpressReservationAgentDTO.setAgentName(aeChannelOfflineAgentCustom.getAgentName());
                            airportExpressReservationAgentDTO.setSaleableType(aeIncreaseStrategyRule.getSaleableType());
                            airportExpressReservationAgentDTO.setRemainderNumber(remainderNumber);
                            HashMap<Integer, BigDecimal> priceMap = AirportExpressService.buildIncreasePrice(airportExpress, aeIncreaseStrategyRule, Channel.AGENT.getCode());
                            airportExpressReservationAgentDTO.setAdultPrice(priceMap.get(0));
                            airportExpressReservationAgentDTO.setChildrenPrice(priceMap.get(1));
                            reservationAgentDTOList.add(airportExpressReservationAgentDTO);
                        }
                    }
                }
            }
        } else {
            // 查询API初始化配置
            AirportExpressInitializationSettings airportExpressInitializationSettings = airportExpressInitializationSettingsMapper.selectCheckSetting(Channel.AGENT.getCode());
            if (airportExpressInitializationSettings == null) {
                // 已设置初始化加幅规则-但未选中线下自营加幅
                return Result.success(reservationAgentDTOList);
            }
            AirportExpressIncreaseStrategyRule aeIncreaseStrategyRule = EntityUtil.copy(airportExpressInitializationSettings, AirportExpressIncreaseStrategyRule.class);
            // 默认售票数量无限制
            aeIncreaseStrategyRule.setSaleableType(1);
            HashMap<Integer, BigDecimal> priceRemainderMap = AirportExpressService.buildIncreasePrice(airportExpress, aeIncreaseStrategyRule, Channel.AGENT.getCode());
            // 获取所有代理商
            List<SysAgentQueryListDTO> sysAgentQueryListDTOS = getSysBigClientQueryListDTOS();
            for (SysAgentQueryListDTO sysAgentQueryListDTO : sysAgentQueryListDTOS) {
                AirportExpressReservationAgentDTO airportExpressReservationAgentDTO = new AirportExpressReservationAgentDTO();
                airportExpressReservationAgentDTO.setId(sysAgentQueryListDTO.getId());
                airportExpressReservationAgentDTO.setAgentName(sysAgentQueryListDTO.getGroupCnName());
                airportExpressReservationAgentDTO.setSaleableType(1);
                airportExpressReservationAgentDTO.setAdultPrice(priceRemainderMap.get(0));
                airportExpressReservationAgentDTO.setChildrenPrice(priceRemainderMap.get(1));
                reservationAgentDTOList.add(airportExpressReservationAgentDTO);
            }
        }
        return Result.success(reservationAgentDTOList);
    }

    /**
     * 查询系统代理商列表
     *
     * @return
     */
    private List<SysAgentQueryListDTO> getSysBigClientQueryListDTOS() {
        SysAgentQueryListReq sysAgentQueryListReq = new SysAgentQueryListReq();
        sysAgentQueryListReq.setPageNo(1);
        sysAgentQueryListReq.setPageSize(1000);
        PageResponse<SysAgentQueryListDTO> sysAgentQueryListDTOPageResponse = sysAgentService.queryAgentListAll(sysAgentQueryListReq);
        return sysAgentQueryListDTOPageResponse.getRecords();
    }


    @Override
    public AirportExpressInfoDTO selectInfo(Long id) {
        AirportExpress airportExpress = airportExpressMapper.selectById(id);
        if (airportExpress == null) {
            // 无机场快线
            throw new BusinessException(SystemError.AIREXPRESS_50004);
        }
        AirportExpressInfoDTO airportExpressDTO = EntityUtil.copy(airportExpress, AirportExpressInfoDTO.class);
        Integer agentSaleType = airportExpressIncreaseStrategyMapper.selectAgentSaleTypeByIdDate(id, LocalDate.now());
        if (agentSaleType != null && agentSaleType >= 2 && agentSaleType <= 3) {//判断是否可以使用代理商
            airportExpressDTO.setCanUseAgent(true);
        } else {
            airportExpressDTO.setCanUseAgent(false);
        }
        // 查询退改手续费
        BigDecimal cancellationCharge = getCancellationCharge(airportExpress);
        airportExpressDTO.setCancellationCharge(cancellationCharge);
        return airportExpressDTO;
    }

    /**
     * 获取退改手续费
     *
     * @param airportExpress
     * @return
     */
    private BigDecimal getCancellationCharge(AirportExpress airportExpress) {
        if (Arrays.asList(1, 2).contains(airportExpress.getServiceChargeType())) {
            // 产品设置-退改手续费
            if (Objects.equals(airportExpress.getServiceChargeType(), ServiceChargeType.PERCENTAGE.getCode())) {
                BigDecimal percentage = airportExpress.getServiceCharge().divide(new BigDecimal("100"));
                return airportExpress.getAdultPrice().multiply(percentage);
            } else if (Objects.equals(airportExpress.getServiceChargeType(), ServiceChargeType.FIXED.getCode())) {
                return airportExpress.getServiceCharge();
            } else {
                throw new BusinessException(SystemError.AIREXPRESS_50005);
            }
        } else {
            // API初始化设置-退改手续费
            AirportExpressInitializationSettings airportExpressInitializationSettings = airportExpressInitializationSettingsMapper.selectAll();
            if (Objects.equals(airportExpressInitializationSettings.getServiceChargeType(), ServiceChargeType.PERCENTAGE.getCode())) {
                BigDecimal percentage = airportExpressInitializationSettings.getServiceCharge().divide(new BigDecimal("100"));
                return airportExpress.getAdultPrice().multiply(percentage);
            } else if (Objects.equals(airportExpressInitializationSettings.getServiceChargeType(), ServiceChargeType.FIXED.getCode())) {
                return airportExpressInitializationSettings.getServiceCharge();
            } else {
                throw new BusinessException(SystemError.AIREXPRESS_50006);
            }
        }
    }

    @Override
    public Result<AirportExpressInfoDTO> selectDetail(Long id) {
        AirportExpress airportExpress = airportExpressMapper.selectById(id);
        if (airportExpress == null) {
            // 无机场快线
            throw new BusinessException(SystemError.AIREXPRESS_50004);
        }
        AirportExpressInfoDTO airportExpressDTO = EntityUtil.copy(airportExpress, AirportExpressInfoDTO.class);
        if (airportExpress.getServiceChargeType() == null) {
            throw new BusinessException(SystemError.AIREXPRESS_50004);
        }
        // 查询退改手续费
        BigDecimal cancellationCharge = getCancellationCharge(airportExpress);
        airportExpressDTO.setCancellationCharge(cancellationCharge);

        // 查询加幅策略列表
        List<AirportExpressIncreaseStrategy> aeIncreaseStrategyList = airportExpressIncreaseStrategyMapper.selectList(new QueryWrapper<AirportExpressIncreaseStrategy>().lambda()
                .eq(AirportExpressIncreaseStrategy::getAirportExpressId, id));
        TreeMap<LocalDate, AirportExpressDetailDTO> dateRuleMap = buildAirportExpressRuleList(aeIncreaseStrategyList);
        airportExpressDTO.setDateRuleInfoMap(dateRuleMap);
        return Result.success(airportExpressDTO);
    }

    /**
     * 根据部门信息，递归查询加幅策略-线下自营信息
     *
     * @param sysDepartmentDTO 部门信息
     * @param ids              加幅策略id
     * @return 加幅策略-线下自营信息
     */
    private void findParentDepartmentId(SysDepartmentDTO sysDepartmentDTO, List<Long> ids) {
        if (sysDepartmentDTO.getParentId() != null && sysDepartmentDTO.getParentId() > 0) {
            // 查找上級部門
            SysDepartmentDTO sysDepartmentDTOTemp = sysDepartmentService.queryOne(sysDepartmentDTO.getParentId());
            List<Long> longs = sysDepartmentService.queryUserIdsByDeptId(sysDepartmentDTOTemp.getId());
            ids.addAll(longs);
            findParentDepartmentId(sysDepartmentDTOTemp, ids);
        }
    }

    /**
     * 计算可售数量
     *
     * @param aeIncreaseStrategyRule
     */
    private int buildRemainderNumber(AirportExpressIncreaseStrategyRule aeIncreaseStrategyRule) {
        if (aeIncreaseStrategyRule != null && Objects.equals(aeIncreaseStrategyRule.getSaleableType(), OrderAirexpressConstants.SALE_TYPE_LIMIT)) {
            int saleableNumber = aeIncreaseStrategyRule.getSaleableNumber() == null ? 0 : aeIncreaseStrategyRule.getSaleableNumber();
            int soldNumber = aeIncreaseStrategyRule.getSoldNumber() == null ? 0 : aeIncreaseStrategyRule.getSoldNumber();
            return saleableNumber - soldNumber;
        }
        return 0;
    }

    /**
     * 组装每天的加幅策略表
     *
     * @param aeIncreaseStrategyList
     * @return
     */
    private TreeMap<LocalDate, AirportExpressDetailDTO> buildAirportExpressRuleList(List<AirportExpressIncreaseStrategy> aeIncreaseStrategyList) {
        HashMap<LocalDate, AirportExpressDetailDTO> localDateRuleInfoMap = new HashMap<>();
        List<Long> strategyIds = aeIncreaseStrategyList.stream().map(AirportExpressIncreaseStrategy::getId).collect(Collectors.toList()); // 加幅策略IDList
        List<Long> strategyOfflineSelfIds = aeIncreaseStrategyList.stream().filter(o -> o.getSelfSalePermissionId() != null)
                .map(AirportExpressIncreaseStrategy::getId).collect(Collectors.toList()); // 加幅策略-含有线下自营的IDList
        List<Long> strategyOfflineAgentIds = aeIncreaseStrategyList.stream().filter(o -> o.getAgentSalePermissionId() != null)
                .map(AirportExpressIncreaseStrategy::getId).collect(Collectors.toList()); // 加幅策略-含有线下代理的IDList
        // 查询当前加幅策略-所有规则列表
        List<AirportExpressIncreaseStrategyRule> aeIncreaseStrategyRules = airportExpressIncreaseStrategyRuleMapper.selectList(new QueryWrapper<AirportExpressIncreaseStrategyRule>().lambda()
                .in(AirportExpressIncreaseStrategyRule::getIncreaseStrategyId, strategyIds));
        // 查询加幅策略-选择线下自营
        List<AirportExpressChannelOfflineSelfCustom> aeChannelOfflineSelfCustoms = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(strategyOfflineSelfIds)) {
            aeChannelOfflineSelfCustoms = airportExpressChannelOfflineSelfCustomMapper.selectList(new QueryWrapper<AirportExpressChannelOfflineSelfCustom>().lambda()
                    .in(AirportExpressChannelOfflineSelfCustom::getIncreaseStrategyId, strategyOfflineSelfIds)
                    .eq(AirportExpressChannelOfflineSelfCustom::getIsDeleted, IsDeletedCode.NO.getCode()));
        }
        // 查询加幅策略-选择线下代理
        List<AirportExpressChannelOfflineAgentCustom> aeChannelOfflineAgentCustoms = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(strategyOfflineAgentIds)) {
            aeChannelOfflineAgentCustoms = airportExpressChannelOfflineAgentCustomMapper.selectList(new QueryWrapper<AirportExpressChannelOfflineAgentCustom>().lambda()
                    .in(AirportExpressChannelOfflineAgentCustom::getIncreaseStrategyId, strategyOfflineAgentIds)
                    .eq(AirportExpressChannelOfflineAgentCustom::getIsDeleted, IsDeletedCode.NO.getCode()));
        }
        // 查询加幅策略-线上自营
        List<AirportExpressChannelOnlineSelfPlatform> aeChannelOnlineSelfPlatforms = airportExpressChannelOnlineSelfPlatformMapper.selectList(new QueryWrapper<AirportExpressChannelOnlineSelfPlatform>().lambda()
                .in(AirportExpressChannelOnlineSelfPlatform::getIncreaseStrategyId, strategyIds)
                .eq(AirportExpressChannelOnlineSelfPlatform::getIsDeleted, IsDeletedCode.NO.getCode()));
        // 查询加幅策略-线上第三方
        List<AirportExpressChannelOnlineThirdPlatform> aeChannelOnlineThirds = airportExpressChannelOnlineThirdPlatformMapper.selectList(new QueryWrapper<AirportExpressChannelOnlineThirdPlatform>().lambda()
                .in(AirportExpressChannelOnlineThirdPlatform::getIncreaseStrategyId, strategyIds)
                .in(AirportExpressChannelOnlineThirdPlatform::getIsDeleted, IsDeletedCode.NO.getCode()));
        // 查询加幅策略-日期列表
        List<AirportExpressIncreaseStrategyDate> aeIncreaseStrategyDateList = airportExpressIncreaseStrategyDateMapper.selectList(new QueryWrapper<AirportExpressIncreaseStrategyDate>().lambda()
                .in(AirportExpressIncreaseStrategyDate::getIncreaseStrategyId, strategyIds));
        for (AirportExpressIncreaseStrategy aeIncreaseStrategy : aeIncreaseStrategyList) {
            List<AirportExpressIncreaseStrategyDateRuleInfoDTO> offlineRuleList = new ArrayList<>();
            List<AirportExpressIncreaseStrategyDateRuleInfoDTO> onlineRuleList = new ArrayList<>();
            // 加幅策略-所有线下自营
            if (aeIncreaseStrategy.getSelfSalePermissionType() != null) {
                if (OrderAirexpressConstants.SALE_CHANNEL_TYPE_ALL == aeIncreaseStrategy.getSelfSalePermissionType()) {
                    List<AirportExpressIncreaseStrategyRule> ruleList = aeIncreaseStrategyRules.stream().filter(rule -> aeIncreaseStrategy.getSelfSalePermissionId().equals(rule.getId())).collect(Collectors.toList());
                    AirportExpressIncreaseStrategyDateRuleInfoDTO strategyRuleInfoDTO = EntityUtil.copy(ruleList.get(0), AirportExpressIncreaseStrategyDateRuleInfoDTO.class);
                    strategyRuleInfoDTO.setChannelFullName("线下自营渠道-所有");
                    //构建剩余可售数量
                    buildRemainder(strategyRuleInfoDTO);
                    offlineRuleList.add(strategyRuleInfoDTO);
                } else if (OrderAirexpressConstants.SALE_CHANNEL_TYPE_SELECTED == aeIncreaseStrategy.getSelfSalePermissionType()) {
                    // 组装所属加幅规则
                    for (AirportExpressChannelOfflineSelfCustom aeChannelOfflineSelfCustom : aeChannelOfflineSelfCustoms) {
                        List<AirportExpressIncreaseStrategyRule> ruleList = aeIncreaseStrategyRules.stream().filter(rule -> aeChannelOfflineSelfCustom.getId().equals(rule.getCustomId())).collect(Collectors.toList());
                        AirportExpressIncreaseStrategyDateRuleInfoDTO strategyRuleInfoDTO = EntityUtil.copy(ruleList.get(0), AirportExpressIncreaseStrategyDateRuleInfoDTO.class);
                        strategyRuleInfoDTO.setChannelFullName("线下自营渠道-" + aeChannelOfflineSelfCustom.getName());
                        buildRemainder(strategyRuleInfoDTO);
                        offlineRuleList.add(strategyRuleInfoDTO);
                    }
                }
            }
            if (aeIncreaseStrategy.getAgentSalePermissionType() != null) {
                // 加幅策略-所有线下代理
                if (OrderAirexpressConstants.SALE_CHANNEL_TYPE_ALL == aeIncreaseStrategy.getAgentSalePermissionType()) {
                    List<AirportExpressIncreaseStrategyRule> ruleList = aeIncreaseStrategyRules.stream().filter(rule -> aeIncreaseStrategy.getAgentSalePermissionId().equals(rule.getId())).collect(Collectors.toList());
                    AirportExpressIncreaseStrategyDateRuleInfoDTO strategyRuleInfoDTO = EntityUtil.copy(ruleList.get(0), AirportExpressIncreaseStrategyDateRuleInfoDTO.class);
                    strategyRuleInfoDTO.setChannelFullName("线下代理渠道-所有");
                    buildRemainder(strategyRuleInfoDTO);
                    offlineRuleList.add(strategyRuleInfoDTO);
                } else if (OrderAirexpressConstants.SALE_CHANNEL_TYPE_SELECTED == aeIncreaseStrategy.getAgentSalePermissionType()) {
                    // 组装所属加幅规则
                    for (AirportExpressChannelOfflineAgentCustom aeChannelOfflineAgentCustom : aeChannelOfflineAgentCustoms) {
                        List<AirportExpressIncreaseStrategyRule> ruleList = aeIncreaseStrategyRules.stream().filter(rule -> aeChannelOfflineAgentCustom.getId().equals(rule.getCustomId())).collect(Collectors.toList());
                        AirportExpressIncreaseStrategyDateRuleInfoDTO strategyRuleInfoDTO = EntityUtil.copy(ruleList.get(0), AirportExpressIncreaseStrategyDateRuleInfoDTO.class);
                        strategyRuleInfoDTO.setChannelFullName("线下代理渠道-" + aeChannelOfflineAgentCustom.getAgentName());
                        buildRemainder(strategyRuleInfoDTO);
                        offlineRuleList.add(strategyRuleInfoDTO);
                    }
                }
            }
            // 查询加幅策略-线上自营-组装所属加幅规则
            for (AirportExpressChannelOnlineSelfPlatform aeChannelOnlineSelfPlatform : aeChannelOnlineSelfPlatforms) {
                List<AirportExpressIncreaseStrategyRule> ruleList = aeIncreaseStrategyRules.stream().filter(rule -> aeChannelOnlineSelfPlatform.getId().equals(rule.getCustomId())).collect(Collectors.toList());
                AirportExpressIncreaseStrategyDateRuleInfoDTO strategyRuleInfoDTO = EntityUtil.copy(ruleList.get(0), AirportExpressIncreaseStrategyDateRuleInfoDTO.class);
                strategyRuleInfoDTO.setChannelFullName("线上官方自营渠道-" + aeChannelOnlineSelfPlatform.getChannelName());

                buildRemainder(strategyRuleInfoDTO);
                onlineRuleList.add(strategyRuleInfoDTO);
            }
            // 查询加幅策略-线上第三方-组装所属加幅规则
            for (AirportExpressChannelOnlineThirdPlatform aeChannelOnlineThirdPlatform : aeChannelOnlineThirds) {
                List<AirportExpressIncreaseStrategyRule> ruleList = aeIncreaseStrategyRules.stream().filter(rule -> aeChannelOnlineThirdPlatform.getId().equals(rule.getCustomId())).collect(Collectors.toList());
                AirportExpressIncreaseStrategyDateRuleInfoDTO strategyRuleInfoDTO = EntityUtil.copy(ruleList.get(0), AirportExpressIncreaseStrategyDateRuleInfoDTO.class);
                strategyRuleInfoDTO.setChannelFullName("线上第三方渠道-" + aeChannelOnlineThirdPlatform.getPlatformName());
                buildRemainder(strategyRuleInfoDTO);
                onlineRuleList.add(strategyRuleInfoDTO);
            }
            AirportExpressDetailDTO airportExpressDetailDTO = new AirportExpressDetailDTO(offlineRuleList, onlineRuleList);
            // 组装日期map
            for (AirportExpressIncreaseStrategyDate airportExpressIncreaseStrategyDate : aeIncreaseStrategyDateList) {
                long diffDay = airportExpressIncreaseStrategyDate.getDateEnd().toEpochDay() - airportExpressIncreaseStrategyDate.getDateBegin().toEpochDay();
                for (int i = 0; i <= diffDay; i++) {
                    localDateRuleInfoMap.put(airportExpressIncreaseStrategyDate.getDateBegin().plusDays(i), airportExpressDetailDTO);
                }
            }
        }
        TreeMap<LocalDate, AirportExpressDetailDTO> localDateListTreeMap = new TreeMap<>(LocalDate::compareTo);
        localDateListTreeMap.putAll(localDateRuleInfoMap);
        return localDateListTreeMap;
    }

    /**
     * 构建剩余可售数
     *
     * @param strategyRuleInfoDTO
     */
    private void buildRemainder(AirportExpressIncreaseStrategyDateRuleInfoDTO strategyRuleInfoDTO) {
        if (strategyRuleInfoDTO.getSaleableType() != null && strategyRuleInfoDTO.getSaleableType() == OrderAirexpressConstants.SALE_TYPE_LIMIT) {
            int soldNumber = strategyRuleInfoDTO.getSoldNumber() == null ? 0 : strategyRuleInfoDTO.getSoldNumber();
            int saleableNumber = strategyRuleInfoDTO.getSaleableNumber() == null ? 0 : strategyRuleInfoDTO.getSaleableNumber();
            strategyRuleInfoDTO.setRemainderNumber(saleableNumber - soldNumber);
        }
    }

    @Override
    public AirportExpressPriceRemainderDTO selectPriceRemainderAndLock(AirportExpressIncreaseStrategyPriceQueryReq priceQueryReq) {
        AirportExpressPriceRemainderDTO airportExpressPriceRemainderDTO = new AirportExpressPriceRemainderDTO();
        LocalDate nowDate = LocalDate.now();
        AirportExpress airportExpress = airportExpressMapper.selectOne(Wrappers.<AirportExpress>lambdaQuery()
                .eq(AirportExpress::getId, priceQueryReq.getAirportExpressId())
                .eq(AirportExpress::getOnShelfStatus, SaleOnShelfStatusCode.ON_SHELF_STATUS_1.getCode())
                .eq(AirportExpress::getSaleStatus, SaleOnShelfStatusCode.SALE_STATUS_1.getCode())
                .eq(AirportExpress::getIsDeleted, IsDeletedCode.NO.getCode()));
        if (airportExpress == null) {
            throw new BusinessException(SystemError.AIREXPRESS_50015);
        }
        airportExpressPriceRemainderDTO.setTicketTypeNameCn(airportExpress.getTicketTypeNameCn());
        airportExpressPriceRemainderDTO.setTicketTypeNameEn(airportExpress.getTicketTypeNameEn());
        AirportExpressIncreaseStrategy airportExpressIncreaseStrategy = airportExpressIncreaseStrategyMapper.selectByAirportExpressIdNowDate(priceQueryReq.getAirportExpressId(), nowDate.toString());
        // 获取加幅策略规则
        AirportExpressIncreaseStrategyRule aeIncreaseStrategyRule = getOfflineSelfRule(priceQueryReq, airportExpressIncreaseStrategy);
        Integer remainderNumber = null;
        // 机场快线-加幅规则失效后，按照初始化设置查询加幅规则
        if (aeIncreaseStrategyRule != null) {
            if (aeIncreaseStrategyRule.getSaleableType() == OrderAirexpressConstants.SALE_TYPE_LIMIT) {
                // 票数有限制，计算余票数量
                int saleableNumber = aeIncreaseStrategyRule.getSaleableNumber() == null ? 0 : aeIncreaseStrategyRule.getSaleableNumber();
                int soldNumber = aeIncreaseStrategyRule.getSoldNumber() == null ? 0 : aeIncreaseStrategyRule.getSoldNumber();
                remainderNumber = saleableNumber - soldNumber;
                if (priceQueryReq.getTouristNumber() > remainderNumber) {
                    // 旅客人数大于余票数量
                    throw new BusinessException(SystemError.AIREXPRESS_ORDER_60000);
                }
                // 锁定票数 AtomicIncreaseSoldNumber
                AirportExpressIncreaseStrategyRule updateStrategyRule = new AirportExpressIncreaseStrategyRule();
                updateStrategyRule.setId(aeIncreaseStrategyRule.getId());
                updateStrategyRule.setSoldNumber(soldNumber + priceQueryReq.getTouristNumber());
                airportExpressIncreaseStrategyRuleMapper.updateById(updateStrategyRule);
            }
        } else {
            AirportExpressInitializationSettings airportExpressInitializationSettings = airportExpressInitializationSettingsMapper.selectCheckSetting(priceQueryReq.getSaleChannelId());
            aeIncreaseStrategyRule = EntityUtil.copy(airportExpressInitializationSettings, AirportExpressIncreaseStrategyRule.class);
            if (airportExpressInitializationSettings == null) {
                // 未设置初始化API设置,暂不售卖
                throw new BusinessException(SystemError.AIREXPRESS_ORDER_60034);
            }
            // 默认售票数量无限制
            aeIncreaseStrategyRule.setSaleableType(OrderAirexpressConstants.SALE_TYPE_UNLIMITED);
        }
        HashMap<Integer, BigDecimal> priceMap = AirportExpressService.buildIncreasePrice(airportExpress, aeIncreaseStrategyRule, priceQueryReq.getSaleChannelId());
        airportExpressPriceRemainderDTO.setAdultCostPrice(airportExpress.getAdultPrice());
        airportExpressPriceRemainderDTO.setChildrenCostPrice(airportExpress.getChildrenPrice());
        airportExpressPriceRemainderDTO.setAdultPrice(priceMap.get(0));
        airportExpressPriceRemainderDTO.setChildrenPrice(priceMap.get(1));
        airportExpressPriceRemainderDTO.setSaleableType(aeIncreaseStrategyRule.getSaleableType());
        airportExpressPriceRemainderDTO.setRemainderNumber(remainderNumber);
        return airportExpressPriceRemainderDTO;
    }

    /**
     * 获取机场快线加幅规则，自营规则或代理规则或线上自营或第三方
     *
     * @param priceQueryReq
     * @param airportExpressIncreaseStrategy
     * @return
     */
    private AirportExpressIncreaseStrategyRule getOfflineSelfRule(AirportExpressIncreaseStrategyPriceQueryReq priceQueryReq, AirportExpressIncreaseStrategy airportExpressIncreaseStrategy) {
        AirportExpressIncreaseStrategyRule aeIncreaseStrategyRule = null;
        if (airportExpressIncreaseStrategy != null) {
            if (Channel.AUTARKY.getCode().equals(priceQueryReq.getSaleChannelId())) { // 线下-自營
                if (airportExpressIncreaseStrategy.getSelfSalePermissionType() == OrderAirexpressConstants.SALE_CHANNEL_TYPE_DISABLED) {
                    // 自營禁售
                    throw new BusinessException(SystemError.AIREXPRESS_ORDER_60022);
                } else if (airportExpressIncreaseStrategy.getSelfSalePermissionType() == OrderAirexpressConstants.SALE_CHANNEL_TYPE_ALL) {
                    //当前机场快线-线下自营所有-获取加幅规则
                    aeIncreaseStrategyRule = airportExpressIncreaseStrategyRuleMapper.selectById(airportExpressIncreaseStrategy.getSelfSalePermissionId());

                } else if (airportExpressIncreaseStrategy.getSelfSalePermissionType() == OrderAirexpressConstants.SALE_CHANNEL_TYPE_SELECTED) {
                    //当前机场快线-线下自营选中-获取加幅规则
                    QueryWrapper<AirportExpressChannelOfflineSelfCustom> offlineSelfQueryWrapper = new QueryWrapper<>();
                    offlineSelfQueryWrapper.lambda().eq(AirportExpressChannelOfflineSelfCustom::getRelationId, priceQueryReq.getUserId());
                    offlineSelfQueryWrapper.lambda().eq(AirportExpressChannelOfflineSelfCustom::getIncreaseStrategyId, airportExpressIncreaseStrategy.getId());
                    AirportExpressChannelOfflineSelfCustom airportExpressChannelOfflineSelfCustom = airportExpressChannelOfflineSelfCustomMapper.selectOne(offlineSelfQueryWrapper);
                    if (airportExpressChannelOfflineSelfCustom != null) {
                        // 当前机场快线-线下自营选中-查询加幅规则
                        QueryWrapper<AirportExpressIncreaseStrategyRule> ruleQueryWrapper = new QueryWrapper<>();
                        ruleQueryWrapper.lambda().eq(AirportExpressIncreaseStrategyRule::getCustomId, airportExpressChannelOfflineSelfCustom.getId());
                        aeIncreaseStrategyRule = airportExpressIncreaseStrategyRuleMapper.selectOne(ruleQueryWrapper);

                    } else {
                        SysDepartmentDTO sysDepartmentDTO = sysDepartmentService.queryByUserId(priceQueryReq.getUserId());
//                        airportExpressChannelOfflineSelfCustom = findParentDepartmentId(sysDepartmentDTO, airportExpressIncreaseStrategy.getId());
                        if (airportExpressChannelOfflineSelfCustom != null) {
                            // 当前机场快线-线下自营选中-查询加幅规则
                            QueryWrapper<AirportExpressIncreaseStrategyRule> ruleQueryWrapper = new QueryWrapper<>();
                            ruleQueryWrapper.lambda().eq(AirportExpressIncreaseStrategyRule::getCustomId, airportExpressChannelOfflineSelfCustom.getId());
                            aeIncreaseStrategyRule = airportExpressIncreaseStrategyRuleMapper.selectOne(ruleQueryWrapper);

                        }
                    }
                }
            } else if (Channel.AGENT.getCode().equals(priceQueryReq.getSaleChannelId())) { // 线下-代理
                if (priceQueryReq.getAgentId() == null) {
                    //代理商ID不存在
                    throw new BusinessException(SystemError.AIREXPRESS_50008);
                }
                // 代理禁售
                if (airportExpressIncreaseStrategy.getAgentSalePermissionType() == OrderAirexpressConstants.SALE_CHANNEL_TYPE_DISABLED) {
                    return null;
                } else if (airportExpressIncreaseStrategy.getAgentSalePermissionType() == OrderAirexpressConstants.SALE_CHANNEL_TYPE_ALL) {
                    // 当前机场快线-线下自营所有-获取加幅规则
                    aeIncreaseStrategyRule = airportExpressIncreaseStrategyRuleMapper.selectById(airportExpressIncreaseStrategy.getAgentSalePermissionId());

                } else if (airportExpressIncreaseStrategy.getAgentSalePermissionType() == OrderAirexpressConstants.SALE_CHANNEL_TYPE_SELECTED) {
                    //当前机场快线-线下代理选中-获取代理加幅规则列表
                    QueryWrapper<AirportExpressChannelOfflineAgentCustom> offlineAgentQueryWrapper = new QueryWrapper<>();
                    offlineAgentQueryWrapper.lambda().eq(AirportExpressChannelOfflineAgentCustom::getIncreaseStrategyId, airportExpressIncreaseStrategy.getId());
                    offlineAgentQueryWrapper.lambda().eq(AirportExpressChannelOfflineAgentCustom::getAgentId, priceQueryReq.getAgentId());
                    AirportExpressChannelOfflineAgentCustom airportExpressChannelOfflineAgentCustom = airportExpressChannelOfflineAgentCustomMapper.selectOne(offlineAgentQueryWrapper);
                    if (airportExpressChannelOfflineAgentCustom != null) {
                        // 当前机场快线-线下代理选中-查询加幅规则
                        QueryWrapper<AirportExpressIncreaseStrategyRule> ruleQueryWrapper = new QueryWrapper<>();
                        ruleQueryWrapper.lambda().eq(AirportExpressIncreaseStrategyRule::getCustomId, airportExpressChannelOfflineAgentCustom.getId());
                        aeIncreaseStrategyRule = airportExpressIncreaseStrategyRuleMapper.selectOne(ruleQueryWrapper);

                    }
                }
            } else if (Channel.PLATFORM.getCode().equals(priceQueryReq.getSaleChannelId())) {
                // 线上门店
                //当前机场快线-线下线上门店选中-获取线上门店加幅规则列表
                AirportExpressChannelOnlineSelfPlatform airportExpressChannelOnlineSelfPlatform = airportExpressChannelOnlineSelfPlatformMapper.selectOne(new QueryWrapper<AirportExpressChannelOnlineSelfPlatform>().lambda()
                        .eq(AirportExpressChannelOnlineSelfPlatform::getIncreaseStrategyId, airportExpressIncreaseStrategy.getId())
                        .eq(AirportExpressChannelOnlineSelfPlatform::getChannelId, priceQueryReq.getChannelId())
                        .eq(AirportExpressChannelOnlineSelfPlatform::getIsDeleted, IsDeletedCode.NO.getCode()));
                if (airportExpressChannelOnlineSelfPlatform == null) {
                    return aeIncreaseStrategyRule;
                }
                // 当前机场快线-线下线上门店选中-查询加幅规则
                aeIncreaseStrategyRule = airportExpressIncreaseStrategyRuleMapper.selectOne(new QueryWrapper<AirportExpressIncreaseStrategyRule>().lambda()
                        .eq(AirportExpressIncreaseStrategyRule::getCustomId, airportExpressChannelOnlineSelfPlatform.getId()));
            }
        }
        return aeIncreaseStrategyRule;
    }

    @Override
    public BigDecimal getCancellationChargeById(Long id, BigDecimal receivableAmount) {
        AirportExpress airportExpress = airportExpressMapper.selectById(id);
        if (airportExpress == null) {
            throw new BusinessException(SystemError.AIREXPRESS_50004);
        }
        airportExpress.setAdultPrice(receivableAmount);
        return getCancellationCharge(airportExpress);
    }

    @Override
    public PageResponse<AirportExpressPageDTO> getPage(AirportExpressPageReq airportExpressPageReq) {
        //查询列表
        Page<AirportExpress> airportExpressPage = new Page<>(airportExpressPageReq.getPageNo(), airportExpressPageReq.getPageSize());
        QueryWrapper<AirportExpress> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AirportExpress::getIsDeleted, IsDeletedCode.NO);
        queryWrapper.lambda().eq(AirportExpress::getSaleStatus, 1);
        queryWrapper.lambda().eq(airportExpressPageReq.getProductCode() != null, AirportExpress::getProductCode, airportExpressPageReq.getProductCode());
        queryWrapper.lambda().like(StringUtils.isNotBlank(airportExpressPageReq.getTicketTypeNameCn()), AirportExpress::getTicketTypeNameCn, airportExpressPageReq.getTicketTypeNameCn());
        queryWrapper.lambda().eq(airportExpressPageReq.getSupplierId() != null, AirportExpress::getSupplierId, airportExpressPageReq.getSupplierId());

        queryWrapper.lambda().orderByDesc(AirportExpress::getGmtCreate);
        Page<AirportExpress> iPage = airportExpressMapper.selectPage(airportExpressPage, queryWrapper);
        List<AirportExpress> records = iPage.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return new PageResponse<>(new ArrayList<>(), iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
        }
        List<AirportExpressPageDTO> airportExpressOrderQueryDTOList = EntityUtil.copyList(records, AirportExpressPageDTO.class);
        return new PageResponse<>(airportExpressOrderQueryDTOList, iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
    }

    @Override
    public List<AirportExpressDTO> getListByIds(List<Long> ids) {
        QueryWrapper<AirportExpress> wrapper = new QueryWrapper<>();
        wrapper.lambda().orderByAsc(AirportExpress::getGmtCreate);
        wrapper.lambda().eq(AirportExpress::getIsDeleted, IsDeletedCode.NO.getCode());
        wrapper.lambda().eq(AirportExpress::getSaleStatus, 1);
        wrapper.lambda().in(AirportExpress::getId, ids);
        List<AirportExpress> airportExpressList = airportExpressMapper.selectList(wrapper);
        List<AirportExpressDTO> airportExpressDTOs = EntityUtil.copyList(airportExpressList, AirportExpressDTO.class);
        return airportExpressDTOs;
    }

    @Override
    public TicketNameDTO selectTicketNameById(Long id) {
        AirportExpress airportExpress = airportExpressMapper.selectOne(Wrappers.<AirportExpress>lambdaQuery()
                .eq(AirportExpress::getId, id)
                .eq(AirportExpress::getIsDeleted, IsDeletedCode.NO.getCode())
                .select(AirportExpress::getTicketTypeNameCn, AirportExpress::getTicketTypeNameEn));
        TicketNameDTO ticketNameDTO = EntityUtil.copy(airportExpress, TicketNameDTO.class);
        return ticketNameDTO;
    }

//    /**
//     * 机场快线首页缓存
//     *
//     * @return
//     */
//    @Override
//    @Cacheable(value = RedisConstants.AIR_EXPRESS_HOME_CHAHE, key = "#root.methodName", sync = true)
//    public Result<List<AirportExpressCacheDTO>> selectHomeList() {
//        QueryWrapper<AirportExpress> wrapper = new QueryWrapper<>();
//        wrapper.lambda().eq(AirportExpress::getIsDeleted, IsDeletedCode.NO.getCode());
//        wrapper.lambda().eq(AirportExpress::getSaleStatus, AirExpressCode.SALE_STATUS_1.getCode());
//        wrapper.lambda().eq(AirportExpress::getOnShelfStatus, AirExpressCode.ON_SHELF_STATUS_1.getCode());
//        List<AirportExpress> airportExpressList = airportExpressMapper.selectList(wrapper);
//        List<AirportExpressCacheDTO> airportExpressDTOs = EntityUtil.copyList(airportExpressList, AirportExpressCacheDTO.class);
//        return Result.success(airportExpressDTOs);
//    }

}
